function send(formId) {
    if (trim($("#chatText").val()) == "") {
        return false;
    }
    ajaxStart();
    var url = sendUrl;
    $.ajax({
        type: "POST",
        url: url,
        async: true,
        timeout: 15000, // 30 secondes
        data: $("#" + formId).serialize(), // serializes the form's elements.
        success: function(data) {
            parseSend(data);
            ajaxStop();
            //alert(data); // show response from the php script.
        },
        complete: function(a) {
            //console.log(a);
            ajaxStop();
        }
    });
    return false;
}

function parseSend(data) {
    var jSonTable = eval("(" + data + ")");
    //console.log(jSonTable);
    insertDiscussion(jSonTable.discussion, 'fade');
}

function update(notifNbr) {
    var url = whatsUpUrl + "" + notifNbr;
    $.ajax({
        cache: false,
        timeout: 600000, // 10 minutes
        type: "POST",
        url: url,
        error: function(err) {
            setTimeout(update, 60000); //après1min
        },
        success: function(response) {
            var jSonTable = eval("(" + response + ")");
            if (jSonTable.notifsNumber != -1) {
                notifNbr = trim(jSonTable.notifsNumber);
                $("#notifs").html(jSonTable.notifsNumber);
                $("[id^='ntf']").html("");
                $.each(jSonTable.ntfByUser, function(i, l) {
                    $("#ntf" + l.from_user).html(l.nbr_ntfs);
                });
            }
            if (notifNbr > 0) {
                getNews();       //Joseph : 06 68 40 59 36
            }
            setTimeout(function() {
                update(notifNbr);
                // alert(notifNbr)
            }, 1000); //après 1 sec
        }
    });
}

function getNews() {
    ajaxStart();
    $.ajax({
        async: true,
        cache: false,
        timeout: 600000, // 10 minutes
        type: "POST",
        url: newsUrl,
        error: function() {
            ajaxStop();
            //console.log("error occurred");
        },
        success: function(data) {
            //console.log("data="+data);
            ajaxStop();
            //console.log("parsing data ..");
            parseJson(data);
        },
        complete: function(d) {
            ajaxStop();
        }
    });
}

//parse News returned as Json
function parseJson(data) {
    var jSonTable = eval("(" + data + ")");
    //console.log(jSonTable);
    var notifMoins = 0;
    var notifsToDel = "";
    $.each(jSonTable, function(i, l) {
        ////console.log(l);
        var user = l.object.user.id;
        //triming ;
        user = trim(user);
        withId = $("#withId").val();
        //console.log("user="+user+" with="+withId)
        if (user == withId) {
            insertDiscussion(l.object, 'hightlight');
            notifMoins++;
            if (notifMoins == 1) {
                notifsToDel += l.id;
            }
            else {
                notifsToDel += "," + l.id;
            }
        }
    });
    if (notifMoins > 0) {
        notifsMoins(notifsToDel);
    }
}


function notifsMoins(notifsToDel) {
    $.ajax({
        async: true,
        cache: false,
        timeout: 600000, // 10 minutes
        type: "POST",
        url: delNotifsUrl,
        data: {
            notifsDel: notifsToDel
        },
        error: function() {
            //console.log("error occurred");
        },
        success: function(data) {
            //console.log("deleted notifs number = "+data);
        }
    });
}

function ajaxStart() {
    $("#ajax-loader").show();
}

function ajaxStop() {
    $("#ajax-loader").hide();
}

function trim(str) {
    return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

function loadChatWith(withId) {
    url = withUrl;
    ajaxStart();
    $.ajax({
        async: true,
        cache: false,
        timeout: 120000, // 2 minutes
        type: "POST",
        url: url,
        data: {
            withId: withId
        },
        error: function() {
            ajaxStop();
            //console.log("error occurred");
        },
        success: function(data) {
            ajaxStop();
            //console.log("parsing data for with ..");
            //console.log(data);
            parseWith(data);
            $("#withId").val(withId);
            selectUser(withId);
        },
        complete: function(d) {
            ajaxStop();
        }
    });
}

function selectUser(id) {
    $("[id^='divUser']").removeClass("selectedUser");
    $("#divUser" + id).toggleClass("selectedUser");
}

function parseWith(data) {

    $("#discussion").html("");
    var jSonObject = eval("(" + data + ")");
    console.log(jSonObject)

    $("#chatingWith").html("");
    htmlChatingWith = getUserDiv(jSonObject.to_user);
    console.log(htmlChatingWith);
    $("#chatingWith").html(htmlChatingWith);

    $("#first_name_with").html(jSonObject.to_user.firstname);

    $.each(jSonObject.discussion, function(i, l) {
        insertDiscussion(l, '', 0);
    });

}

function getUserDiv(u) {
    var t = "<div class='divUser' style='width:100%;'>" +
            " <div class='notSelected'>" +
            "<img src='" + tofsUrl + u.tof + "'/>" +
            "</div>" +
            "<div class='notSelected'>" +
            "<p>" + u.firstname + " " + u.lastname + "</p>" +
            "<p>" + u.city + ", " + u.country + "</p>" +
            "<p>" + u.birthday + "</p>" +
            "<p>" + u.statut + "</p>" +
            "</div>" +
            "</div>";
    return t;
}

function insertDiscussion(discussion, effect, scroll) {
    var html = "<div class=\"row\">" +
            "<div class=\"spanG\">" +
            " <img class=\"gravatar\" src=\"" + tofsUrl + discussion.user.tof + "\"/>" +
            "</div>" +
            "<div class=\"author\" >" + discussion.user.firstname +
            "</div>" +
            "<div class=\"time\">"
            + "10:44" +
            "</div>" +
            "</div>";
    html += "<div class=\"row\">" +
            "<div class=\"spanG\"></div>" +
            "<div class=\"spanM\" style=\"\">" + discussion.message + "</div>" + "</div>";
    html += "<div class=\"clear\"></div>";
//    html = '<div class="msg">' +
//                '<div class="chat rounded">' +
//                '<img class="gravatar" src="' + tofsUrl + discussion.user.tof + '" width="23" height="23"/>' +
//                '<h1 class="author">' + discussion.user.firstname + '</h1>' +
//                '<span class="time">10:44</span>' +
//                '</div>' +
//                '<div class="text">' + discussion.message + '</div>' +
//                '</div>';


    var new_item = $(html).hide();
    $("#discussion").append(new_item);

    if (effect == 'fade') {
        new_item.fadeIn();
    }

    else if (effect == '') {
        new_item.show();
    }

    else {
        new_item.show(effect);
    }

    if (scroll != 0) {
        $("#discussion").animate({
            scrollTop: $("#discussion")[0].scrollHeight
        }, 100);
    }
}


function waterMark(accessor) {
    if ($(accessor).val() == "") {
        $(accessor).val($(accessor).attr("title"));
        $(accessor).addClass("tgl");
    }
    $(accessor).focus(function() {
        if ($(this).val() == $(this).attr("title")) {
            $(this).val("");
            $(this).removeClass("tgl");
        }
    }).blur(function() {
        if ($(this).val() == "") {
            $(this).val($(this).attr("title"));
            $(this).addClass("tgl");
        }
        if ($(this).val() == $(this).attr("title")) {
            $(this).addClass("tgl");
        }
    });
}

function search() {
    var frmId = "frm_search";
    url = searchUrl;
    ajaxStart();
    $.ajax({
        async: true,
        cache: false,
        timeout: 120000, // 2 minutes
        type: "POST",
        url: url,
        data: $("#" + frmId).serialize(),
        error: function() {
            ajaxStop();
            //console.log("error occurred");
        },
        success: function(data) {
            ajaxStop();
            parseSearch(data);
        },
        complete: function(d) {
            ajaxStop();
        }
    });
}

function parseSearch(data) {
    //alert(data);
    $("#socialDiv").html(data);
//console.log(data);
}